package com.ciaojian.timer.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.core.config.FuluOpenConfig;
import com.ciaojian.core.constant.RedisConstant;
import com.ciaojian.core.enums.business.CounterClickTypeEnum;
import com.ciaojian.core.model.ClickCounter;
import com.ciaojian.core.util.LogUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Set;

/**
 * 统计
 *
 * @author Atlakyn
 */
@Component
public class ClickMallCounterScheduled {
    @Resource
    private RedisTemplate<String, ClickCounter> redisTemplate;

    @Scheduled(cron = "${scheduled.cron.clickMallCounterTask}")
    public void clickCount() {
        Set<String> keys = redisTemplate.keys(RedisConstant.COUNTER_CLICK.concat("*"));
        // 当天日期
        Date curDate = new Date();
        if (!CollUtil.isEmpty(keys)) {
            keys.forEach(key -> {
                redisTemplate.watch(key);
                ClickCounter counter = redisTemplate.opsForValue().get(key);
                if (counter == null) {
                    counter = new ClickCounter();
                    counter.setType(CounterClickTypeEnum.getByRedisKey(key.replace(RedisConstant.COUNTER_CLICK, "")));
                }
                counter.setDate(curDate);
                counter.insert();
                // 初始化
                redisTemplate.opsForValue().set(key, new ClickCounter());
                redisTemplate.multi();
                LogUtil.writeScheduleLog(String.format("点击次数统计,key:{%s}点击数为:{%s}", counter.getType(), counter.getCount()));
            });
        }
    }
}
